<!-- 性能监控面板 -->
<template>
  <div v-if="showMonitor" class="performance-monitor" :class="{ 'minimized': isMinimized }">
    <!-- 控制栏 -->
    <div class="monitor-header" @click="toggleMinimized">
      <div class="title">
        <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="M3 13l4 4L20 4"/>
        </svg>
        <span>性能监控</span>
        <span v-if="performanceScore" class="score" :class="getScoreClass(performanceScore.overall)">
          {{ performanceScore.overall }}
        </span>
      </div>
      <div class="controls">
        <button @click.stop="refreshData" class="control-btn" title="刷新数据">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M1 4v6h6M23 20v-6h-6"/>
            <path d="M20.49 9A9 9 0 0 0 5.64 5.64L1 10m22 4l-4.64 4.36A9 9 0 0 1 3.51 15"/>
          </svg>
        </button>
        <button @click.stop="exportReport" class="control-btn" title="导出报告">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
            <polyline points="7,10 12,15 17,10"/>
            <line x1="12" y1="15" x2="12" y2="3"/>
          </svg>
        </button>
        <button @click.stop="closeMonitor" class="control-btn" title="关闭">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <line x1="18" y1="6" x2="6" y2="18"/>
            <line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>
      </div>
    </div>

    <!-- 监控内容 -->
    <div v-if="!isMinimized" class="monitor-content">
      <!-- Core Web Vitals -->
      <div class="metrics-section">
        <h3>核心网页指标</h3>
        <div class="metrics-grid">
          <!-- FCP -->
          <div class="metric-card">
            <div class="metric-label">FCP</div>
            <div class="metric-value" :class="getMetricClass('FCP', metrics.FCP)">
              {{ formatMs(metrics.FCP) }}
            </div>
            <div class="metric-desc">首次内容绘制</div>
          </div>
          
          <!-- LCP -->
          <div class="metric-card">
            <div class="metric-label">LCP</div>
            <div class="metric-value" :class="getMetricClass('LCP', metrics.LCP)">
              {{ formatMs(metrics.LCP) }}
            </div>
            <div class="metric-desc">最大内容绘制</div>
          </div>
          
          <!-- FID -->
          <div class="metric-card">
            <div class="metric-label">FID</div>
            <div class="metric-value" :class="getMetricClass('FID', metrics.FID)">
              {{ formatMs(metrics.FID) }}
            </div>
            <div class="metric-desc">首次输入延迟</div>
          </div>
          
          <!-- CLS -->
          <div class="metric-card">
            <div class="metric-label">CLS</div>
            <div class="metric-value" :class="getMetricClass('CLS', metrics.CLS)">
              {{ formatCLS(metrics.CLS) }}
            </div>
            <div class="metric-desc">累积布局偏移</div>
          </div>
        </div>
      </div>

      <!-- 资源统计 -->
      <div class="resources-section">
        <h3>资源统计</h3>
        <div class="resource-stats">
          <div class="stat-item">
            <span class="stat-label">总资源数：</span>
            <span class="stat-value">{{ resourceStats.totalResources }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">总大小：</span>
            <span class="stat-value">{{ formatBytes(resourceStats.totalSize) }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">预加载：</span>
            <span class="stat-value">{{ preloadStats.resourcesPreloaded }}</span>
          </div>
        </div>
      </div>

      <!-- 内存使用 -->
      <div v-if="memoryUsage" class="memory-section">
        <h3>内存使用</h3>
        <div class="memory-bar">
          <div 
            class="memory-fill" 
            :style="{ width: `${memoryUsage.usage}%` }"
            :class="getMemoryClass(memoryUsage.usage)"
          ></div>
        </div>
        <div class="memory-info">
          <span>{{ memoryUsage.used }}MB / {{ memoryUsage.total }}MB ({{ memoryUsage.usage }}%)</span>
        </div>
      </div>

      <!-- 网络状态 -->
      <div v-if="networkStatus" class="network-section">
        <h3>网络状态</h3>
        <div class="network-info">
          <div class="network-item">
            <span class="network-label">连接类型：</span>
            <span class="network-value">{{ networkStatus.effectiveType || 'unknown' }}</span>
          </div>
          <div class="network-item">
            <span class="network-label">下载速度：</span>
            <span class="network-value">{{ networkStatus.downlink || 0 }} Mbps</span>
          </div>
          <div class="network-item">
            <span class="network-label">延迟：</span>
            <span class="network-value">{{ networkStatus.rtt || 0 }} ms</span>
          </div>
        </div>
      </div>

      <!-- 优化建议 -->
      <div v-if="optimizationSuggestions.length > 0" class="suggestions-section">
        <h3>优化建议</h3>
        <ul class="suggestions-list">
          <li v-for="suggestion in optimizationSuggestions" :key="suggestion" class="suggestion-item">
            {{ suggestion }}
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { usePerformance } from '../composables/usePerformance'
import { usePreloadStrategy } from '../composables/usePreload'

interface Props {
  autoStart?: boolean
  position?: 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'
  theme?: 'light' | 'dark'
}

const props = withDefaults(defineProps<Props>(), {
  autoStart: true,
  position: 'bottom-right',
  theme: 'dark'
})

const showMonitor = ref(props.autoStart)
const isMinimized = ref(false)
const updateInterval = ref<number | null>(null)

// 性能监控
const {
  metrics,
  performanceScore,
  memoryUsage,
  networkStatus,
  optimizationSuggestions,
  generatePerformanceReport,
  getResourceMetrics
} = usePerformance()

// 预加载统计
const { getPreloadStats } = usePreloadStrategy()
const preloadStats = computed(() => getPreloadStats())

// 资源统计
const resourceStats = ref({
  totalResources: 0,
  totalSize: 0,
  slowestResources: [],
  largestResources: []
})

// 定期更新数据
onMounted(() => {
  if (props.autoStart) {
    startMonitoring()
  }
})

onUnmounted(() => {
  stopMonitoring()
})

const startMonitoring = () => {
  refreshData()
  updateInterval.value = window.setInterval(refreshData, 5000) // 每5秒更新
}

const stopMonitoring = () => {
  if (updateInterval.value) {
    clearInterval(updateInterval.value)
    updateInterval.value = null
  }
}

const refreshData = () => {
  resourceStats.value = getResourceMetrics()
}

// 控制函数
const toggleMinimized = () => {
  isMinimized.value = !isMinimized.value
}

const closeMonitor = () => {
  showMonitor.value = false
  stopMonitoring()
}

const exportReport = () => {
  const report = generatePerformanceReport()
  const blob = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = `performance-report-${new Date().toISOString().slice(0, 10)}.json`
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
  URL.revokeObjectURL(url)
}

// 工具函数
const formatMs = (value?: number) => {
  if (value === undefined) return '-'
  return `${Math.round(value)}ms`
}

const formatCLS = (value?: number) => {
  if (value === undefined) return '-'
  return value.toFixed(3)
}

const formatBytes = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const getScoreClass = (score: number) => {
  if (score >= 90) return 'excellent'
  if (score >= 70) return 'good'
  if (score >= 50) return 'fair'
  return 'poor'
}

const getMetricClass = (type: string, value?: number) => {
  if (value === undefined) return 'unknown'
  
  switch (type) {
    case 'FCP':
      return value <= 1800 ? 'good' : value <= 3000 ? 'fair' : 'poor'
    case 'LCP':
      return value <= 2500 ? 'good' : value <= 4000 ? 'fair' : 'poor'
    case 'FID':
      return value <= 100 ? 'good' : value <= 300 ? 'fair' : 'poor'
    case 'CLS':
      return value <= 0.1 ? 'good' : value <= 0.25 ? 'fair' : 'poor'
    default:
      return 'unknown'
  }
}

const getMemoryClass = (usage: number) => {
  if (usage < 50) return 'good'
  if (usage < 80) return 'fair'
  return 'poor'
}

// 暴露给父组件的方法
defineExpose({
  show: () => { showMonitor.value = true },
  hide: () => { showMonitor.value = false },
  toggle: () => { showMonitor.value = !showMonitor.value },
  refresh: refreshData,
  export: exportReport
})
</script>

<style scoped lang="scss">
@use '@/styles/variables.scss' as *;

.performance-monitor {
  position: fixed;
  z-index: $z-modal;
  min-width: 320px;
  max-width: 400px;
  background: rgba(0, 0, 0, 0.9);
  border-radius: $border-radius-lg;
  box-shadow: $shadow-xl;
  color: $white;
  font-size: $font-size-sm;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  
  // 位置
  &.top-left { top: 20px; left: 20px; }
  &.top-right { top: 20px; right: 20px; }
  &.bottom-left { bottom: 20px; left: 20px; }
  &.bottom-right { bottom: 20px; right: 20px; }
  
  &.minimized {
    .monitor-content {
      display: none;
    }
  }
}

.monitor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: $spacing-md;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  cursor: pointer;
  user-select: none;
  
  .title {
    display: flex;
    align-items: center;
    gap: $spacing-sm;
    
    .icon {
      width: 16px;
      height: 16px;
      color: $success-color;
    }
    
    .score {
      padding: 2px 6px;
      border-radius: $border-radius-sm;
      font-weight: bold;
      font-size: 12px;
      
      &.excellent { background: $success-color; }
      &.good { background: #2196F3; }
      &.fair { background: $warning-color; color: $black; }
      &.poor { background: $error-color; }
    }
  }
  
  .controls {
    display: flex;
    gap: $spacing-xs;
    
    .control-btn {
      background: none;
      border: none;
      color: $white;
      cursor: pointer;
      padding: 4px;
      border-radius: $border-radius-sm;
      transition: background $transition-fast;
      
      &:hover {
        background: rgba(255, 255, 255, 0.1);
      }
      
      svg {
        width: 14px;
        height: 14px;
      }
    }
  }
}

.monitor-content {
  padding: $spacing-md;
  max-height: 600px;
  overflow-y: auto;
  
  h3 {
    margin: 0 0 $spacing-md 0;
    font-size: $font-size-md;
    font-weight: 600;
    color: $white;
  }
}

.metrics-section {
  margin-bottom: $spacing-lg;
  
  .metrics-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: $spacing-md;
  }
  
  .metric-card {
    background: rgba(255, 255, 255, 0.05);
    padding: $spacing-md;
    border-radius: $border-radius-md;
    text-align: center;
    
    .metric-label {
      font-weight: 600;
      color: $gray-300;
      font-size: 12px;
    }
    
    .metric-value {
      font-size: $font-size-lg;
      font-weight: bold;
      margin: 4px 0;
      
      &.good { color: $success-color; }
      &.fair { color: $warning-color; }
      &.poor { color: $error-color; }
      &.unknown { color: $gray-400; }
    }
    
    .metric-desc {
      font-size: 11px;
      color: $gray-400;
    }
  }
}

.resources-section,
.memory-section,
.network-section {
  margin-bottom: $spacing-lg;
}

.resource-stats,
.network-info {
  display: flex;
  flex-direction: column;
  gap: $spacing-xs;
}

.stat-item,
.network-item {
  display: flex;
  justify-content: space-between;
  
  .stat-label,
  .network-label {
    color: $gray-300;
  }
  
  .stat-value,
  .network-value {
    color: $white;
    font-weight: 500;
  }
}

.memory-bar {
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: $spacing-sm;
  
  .memory-fill {
    height: 100%;
    transition: width 0.3s ease;
    
    &.good { background: $success-color; }
    &.fair { background: $warning-color; }
    &.poor { background: $error-color; }
  }
}

.memory-info {
  text-align: center;
  color: $gray-300;
  font-size: 12px;
}

.suggestions-section {
  .suggestions-list {
    list-style: none;
    padding: 0;
    margin: 0;
    
    .suggestion-item {
      background: rgba(255, 193, 7, 0.1);
      border-left: 3px solid $warning-color;
      padding: $spacing-sm;
      margin-bottom: $spacing-sm;
      border-radius: 0 $border-radius-sm $border-radius-sm 0;
      font-size: 12px;
      color: $gray-200;
    }
  }
}

// 响应式
@media (max-width: $breakpoint-sm) {
  .performance-monitor {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    max-width: none;
    border-radius: 0;
    
    .metrics-grid {
      grid-template-columns: 1fr;
    }
  }
}
</style> 